﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QAbstractSocket>
#include <QDebug>
#include <QMessageBox>
#include <QNetworkInterface>
#include "mycombobox.h"
#pragma execution_character_set("utf-8")
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_tcpServer = new QTcpServer(this);

    connect(m_tcpServer,&QTcpServer::newConnection,this,&MainWindow::onNewConnect);
    connect(ui->cB_children,&MyComboBox::comboBoxClicked,this,&MainWindow::on_comboboxClicked);

    ui->pB_diListen->setEnabled(false);
    ui->pB_disconnect->setEnabled(false);
    ui->pB_listen->setEnabled(true);
    ui->pB_send->setEnabled(false);

    QList<QHostAddress> addresss =  QNetworkInterface::allAddresses();
    for(QHostAddress temp : addresss){
        // 将IPV4的地址加入combox
        if(temp.protocol() == QAbstractSocket::IPv4Protocol){
            ui->cB_ip->addItem(temp.toString());
        }
    }

}

MainWindow::~MainWindow()
{
    delete ui;

}

void MainWindow::onNewConnect()
{
    //当前连接的客户端
    if(m_tcpServer->hasPendingConnections()){
        m_tcpSocket = m_tcpServer->nextPendingConnection();
        ui->tE_recve->insertPlainText("客户端地址："+m_tcpSocket->peerAddress().toString().mid(7,11)+
                                      "\n客户端端口号："+QString::number(m_tcpSocket->peerPort())+"\n");
    }
    ui->cB_children->addItem(QString::number(m_tcpSocket->peerPort()));
    ui->cB_children->setCurrentText(QString::number(m_tcpSocket->peerPort()));
    if(!ui->pB_send->isEnabled())
        ui->pB_send->setEnabled(true);
    //断开连接
    //    connect(m_tcpSocket,&QTcpSocket::disconnected,this,&MainWindow::stateChange);
    connect(m_tcpSocket,&QTcpSocket::stateChanged,this,&MainWindow::mstateChanged);
    //socket有数据时会发送readyRead信号
    connect(m_tcpSocket,&QTcpSocket::readyRead,this,&MainWindow::onReadMsg);
}

void MainWindow::onReadMsg()
{
    //服务端将客户端发来的数据显示到标签上
    QTcpSocket *temSocket = qobject_cast<QTcpSocket *>(sender());
    QByteArray bt=temSocket->readAll(); //使用readall接收数据
    ui->tE_recve->insertPlainText(bt);

    ui->tE_recve->moveCursor(QTextCursor::End);
    ui->tE_recve->ensureCursorVisible();
}

void MainWindow::stateChange()
{
    /*QList<QTcpSocket *> tcpSocketClients= m_tcpServer->findChildren<QTcpSocket *>();
    ui->tE_recve->insertPlainText("已断开连接\n");
    ui->cB_children->clear();
    for(QTcpSocket* temp : tcpSocketClients){
        if(QString::number(temp->peerPort()) != "0")
            ui->cB_children->addItem(QString::number(temp->peerPort()));
    }
    if(tcpSocketClients.isEmpty())
        ui->pB_send->setEnabled(false);*/


}

void MainWindow::mstateChanged(QAbstractSocket::SocketState socketState)
{
    QTcpSocket *tempSocket = qobject_cast<QTcpSocket * >(sender());
    switch (socketState) {
    case QAbstractSocket::UnconnectedState:
        ui->tE_recve->insertPlainText("客户端断开");
        ui->cB_children->removeItem(ui->cB_children->findText(QString::number(tempSocket->peerPort())));
        tempSocket->deleteLater();

        if(ui->cB_children->count() == 0){
            ui->pB_send->setEnabled(false);
        }
        break;
    case QAbstractSocket::ConnectedState:
    case QAbstractSocket::ConnectingState:
        ui->tE_recve->insertPlainText("客户已连接");
        break;
    default:
        break;
    }
}

void MainWindow::on_pB_listen_clicked()
{
    int portNum = ui->lE_port->text().toInt();
    qDebug() << "port: " << ui->lE_port->text();
    if(!m_tcpServer->listen(QHostAddress::Any,portNum)){
        qDebug() << "connect error ";
        QMessageBox msgBox;
        msgBox.setText("监听失败 端口被占用");
        msgBox.exec();
        return;
    }
    ui->pB_diListen->setEnabled(true);
    ui->pB_disconnect->setEnabled(true);
    ui->pB_listen->setEnabled(false);
}

void MainWindow::on_pB_diListen_clicked()
{
    QList<QTcpSocket *> tcpSocketClients= m_tcpServer->findChildren<QTcpSocket *>();
    for(QTcpSocket* temp : tcpSocketClients){
        temp->close();
    }
    m_tcpServer->close();
    ui->pB_diListen->setEnabled(false);
    ui->pB_disconnect->setEnabled(false);
    ui->pB_listen->setEnabled(true);
}

void MainWindow::on_pB_disconnect_clicked()
{
    QList<QTcpSocket *> tcpSocketClients= m_tcpServer->findChildren<QTcpSocket *>();
    for(QTcpSocket* temp : tcpSocketClients){
        temp->close();
    }
    m_tcpServer->close();
    this->close();
}

void MainWindow::on_pB_send_clicked()
{
    QList<QTcpSocket *> tcpSocketClients= m_tcpServer->findChildren<QTcpSocket *>();
    if(tcpSocketClients.isEmpty()){
        QMessageBox msgBox;
        msgBox.setText("没有连接.");
        msgBox.exec();
        ui->pB_send->setEnabled(false);
        return;
    }

    if(ui->cB_children->currentText() != "all"){
        QString currentName = ui->cB_children->currentText();
        for(QTcpSocket * tempSocked : tcpSocketClients){
            if(QString::number(tempSocked->peerPort()) == currentName){
                tempSocked->write(ui->tE_send->toPlainText().toUtf8());
            }
        }
    }else{
        for(QTcpSocket* temp : tcpSocketClients){
            temp->write(ui->tE_send->toPlainText().toUtf8());
        }
    }
}

void MainWindow::on_comboboxClicked()
{
    ui->cB_children->clear();
    QList<QTcpSocket *> tcpSocketClients= m_tcpServer->findChildren<QTcpSocket *>();
    for(QTcpSocket* temp : tcpSocketClients){
        if(QString::number(temp->peerPort()) != "0")
            ui->cB_children->addItem(QString::number(temp->peerPort()));
    }
    ui->cB_children->addItem("all");
}

void MainWindow::on_cB_children_activated(int index)
{
    indexChild = index;
}
